﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace Cotizav.Presentacion.WinForms.Equipo
{
    public partial class RegistroEquipo : Form
    {
        private List<Entidades.Caracteristica> listCaracteristica;
        private List<Entidades.ListaTarifa> listListaTarifa;

        public RegistroEquipo()
        {
            InitializeComponent();

            listCaracteristica = new List<Entidades.Caracteristica>();
            listListaTarifa = new List<Entidades.ListaTarifa>();
        }

        private void RegistroEquipo_Load(object sender, EventArgs e)
        {
            LoadListMarca();
        }

        private void LoadListMarca()
        {
            LogicaNegocio.MarcaBLL marcaBLL = new LogicaNegocio.MarcaBLL();
            cmbMarca.DataSource = marcaBLL.Listar();
            cmbMarca.ValueMember = "IdMarca";
            cmbMarca.DisplayMember = "NombreMarca";
            cmbMarca.SelectedIndex = -1;
        }

        private void cmbMarca_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (cmbMarca.SelectedIndex >= 0)
            {
                LogicaNegocio.ModeloBLL modeloBLL = new LogicaNegocio.ModeloBLL();
                cmbModelo.DataSource = modeloBLL.Listar();
                cmbModelo.ValueMember = "IdModelo";
                cmbModelo.DisplayMember = "NombreModelo";
                cmbModelo.SelectedIndex = -1;
            }
        }

        private void LimpiarTabInformacionBasica()
        {
            txtCodigo.ResetText();
            txtDescripcion.ResetText();
            chkEsAlquiler.Checked = false;
            chkEsVenta.Checked = false;
            cmbModelo.DataSource = null;
            LoadListMarca();
        }

        private void LimpiarTabListaTarifa()
        {
            txtnumDia.ResetText();
            txtnumSemana.ResetText();
            txtnumMes.ResetText();
            txtTarifaHoraDia.ResetText();
            txtTarifaHoraSemana.ResetText();
            txtTarifaHoraMes.ResetText();
            txtTarifaDia.ResetText();
            txtTarifaSemana.ResetText();
            txtTarifaMes.ResetText();

            cmbMoneda.SelectedIndex = -1;

            listListaTarifa.Clear();
        }

        private void LimpiarTabCaracteristica()
        {
            LimpiarFormularioCaracteristica();
            listCaracteristica.Clear();
            gridCaracteristicas.DataSource = null;
        }

        #region Tarifas

        private void calcularTarifasDia()
        {
            if (!string.IsNullOrWhiteSpace(txtnumDia.Text))
            {
                try
                {
                    double numDia = Convert.ToDouble(txtnumDia.Text);

                    if (!string.IsNullOrWhiteSpace(txtTarifaHoraDia.Text))
                    {
                        double tarifa = Convert.ToDouble(txtTarifaHoraDia.Text);
                        double tarifaxDia = numDia * tarifa;
                        txtTarifaDia.Text = tarifaxDia.ToString("N", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        txtTarifaDia.ResetText();
                    }
                }
                catch (FormatException)
                {
                    if (txtnumDia.Text != ".")
                    {
                        txtnumDia.ResetText();
                    }
                }
            }
            else
            {
                txtnumDia.ResetText();
                txtTarifaDia.ResetText();
            }
        }

        private void calcularTarifasSemana()
        {
            if (!string.IsNullOrWhiteSpace(txtnumSemana.Text))
            {
                try
                {
                    double numSemana = Convert.ToDouble(txtnumSemana.Text);

                    if (!string.IsNullOrWhiteSpace(txtTarifaHoraSemana.Text))
                    {
                        double tarifa = Convert.ToDouble(txtTarifaHoraSemana.Text);
                        double tarifaxSemana = numSemana * tarifa;
                        txtTarifaSemana.Text = tarifaxSemana.ToString("N", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        txtTarifaSemana.ResetText();
                    }
                }
                catch (FormatException)
                {
                    if (txtnumSemana.Text != ".")
                    {
                        txtnumSemana.Text = string.Empty;
                    }
                }
            }
            else
            {
                txtnumSemana.ResetText();
                txtTarifaSemana.ResetText();
            }
        }

        private void calcularTarifasMes()
        {
            if (!string.IsNullOrWhiteSpace(txtnumMes.Text))
            {
                try
                {
                    double numMes = Convert.ToDouble(txtnumMes.Text);

                    if (!string.IsNullOrWhiteSpace(txtTarifaHoraMes.Text))
                    {
                        double tarifa = Convert.ToDouble(txtTarifaHoraMes.Text);
                        double tarifaxMes = numMes * tarifa;
                        txtTarifaMes.Text = tarifaxMes.ToString("N", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        txtTarifaMes.ResetText();
                    }
                }
                catch (FormatException)
                {
                    if (txtnumMes.Text != ".")
                    {
                        txtnumMes.ResetText();
                    }
                }
            }
            else
            {
                txtnumMes.ResetText();
                txtTarifaMes.ResetText();
            }
        }

        private void txtnumDia_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtnumDia_KeyUp(object sender, KeyEventArgs e)
        {
            this.calcularTarifasDia();
        }

        private void txtnumSemana_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtnumSemana_KeyUp(object sender, KeyEventArgs e)
        {
            this.calcularTarifasSemana();
        }

        private void txtnumMes_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtnumMes_KeyUp(object sender, KeyEventArgs e)
        {
            this.calcularTarifasMes();
        }

        private void txtTarifaHoraDia_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtTarifaHoraDia_KeyUp(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtTarifaHoraDia.Text))
            {
                try
                {
                    double tarifaxHora = Convert.ToDouble(txtTarifaHoraDia.Text);
                    double hora = Convert.ToDouble(txtnumDia.Text);
                    double tarifa = hora * tarifaxHora;

                    txtTarifaDia.Text = tarifa.ToString("N");
                }
                catch (FormatException)
                {
                    if (txtTarifaHoraDia.Text != ".")
                    {
                        txtTarifaHoraDia.ResetText();
                    }
                }
            }
            else
            {
                txtTarifaDia.ResetText();
            }
        }

        private void txtTarifaHoraSemana_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtTarifaHoraSemana_KeyUp(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtTarifaHoraSemana.Text))
            {
                try
                {
                    double tarifaxHora = Convert.ToDouble(txtTarifaHoraSemana.Text);
                    double hora = Convert.ToDouble(txtnumSemana.Text);
                    double tarifa = hora * tarifaxHora;

                    txtTarifaSemana.Text = tarifa.ToString("N");
                }
                catch (FormatException)
                {
                    if (txtTarifaHoraSemana.Text != ".")
                    {
                        txtTarifaHoraSemana.ResetText();
                    }
                }
            }
            else
            {
                txtTarifaHoraSemana.ResetText();
            }
        }

        private void txtTarifaHoraMes_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtTarifaHoraMes_KeyUp(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtTarifaHoraMes.Text))
            {
                try
                {
                    double tarifaxHora = Convert.ToDouble(txtTarifaHoraMes.Text);
                    double hora = Convert.ToDouble(txtnumMes.Text);
                    double tarifa = hora * tarifaxHora;

                    txtTarifaMes.Text = tarifa.ToString("N");
                }
                catch (FormatException)
                {
                    if (txtTarifaHoraMes.Text != ".")
                    {
                        txtTarifaHoraMes.ResetText();
                    }
                }
            }
            else
            {
                txtTarifaHoraMes.ResetText();
            }
        }

        #endregion

        #region Caracteristica

        private void LimpiarFormularioCaracteristica()
        {
            txtCaracteristica.ResetText();
            txtDescrip.ResetText();
        }

        private void btnNuevo_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrWhiteSpace(txtCaracteristica.Text))
            {
                if(!string.IsNullOrWhiteSpace(txtDescrip.Text))
                {
                    Entidades.Caracteristica nuevaCaracteristica =
                        new Entidades.Caracteristica()
                        {
                            NombreCaracteristica = txtCaracteristica.Text.Trim(),
                            Descripcion = txtDescrip.Text.Trim(),
                            Activo = 1                            
                        };

                    listCaracteristica.Add(nuevaCaracteristica);

                    gridCaracteristicas.DataSource = null;
                    gridCaracteristicas.DataSource = listCaracteristica;
                    gridCaracteristicas.ClearSelection();

                    LimpiarFormularioCaracteristica();
                }
            }
        }

        private void btnModificar_Click(object sender, EventArgs e)
        {
            if (gridCaracteristicas.SelectedRows.Count > 0)
            {
                int selectedIndex = gridCaracteristicas.SelectedRows[0].Index;

                if (listCaracteristica[selectedIndex] != null)
                {
                    listCaracteristica[selectedIndex].NombreCaracteristica = txtCaracteristica.Text.Trim();
                    listCaracteristica[selectedIndex].Descripcion = txtDescrip.Text.Trim();

                    gridCaracteristicas.DataSource = null;
                    gridCaracteristicas.DataSource = listCaracteristica;
                    gridCaracteristicas.ClearSelection();

                    LimpiarFormularioCaracteristica();
                }
            }
        }
               
        private void btnEliminar_Click(object sender, EventArgs e)
        {
            if (gridCaracteristicas.SelectedRows.Count > 0)
            {
                int selectedIndex = gridCaracteristicas.SelectedRows[0].Index;

                if (listCaracteristica[selectedIndex] != null)
                {
                    listCaracteristica.RemoveAt(selectedIndex);

                    gridCaracteristicas.DataSource = null;
                    gridCaracteristicas.DataSource = listCaracteristica;
                    gridCaracteristicas.ClearSelection();

                    LimpiarFormularioCaracteristica();
                }
            }
        }

        private void gridCaracteristicas_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (gridCaracteristicas.DataSource != null)
            {
                gridCaracteristicas.Columns["IdCaracteristica"].Visible = false;
                gridCaracteristicas.Columns["IdEquipo"].Visible = false;
                gridCaracteristicas.Columns["NombreCaracteristica"].HeaderText = "Característica";
                gridCaracteristicas.Columns["Descripcion"].HeaderText = "Descripción";
                gridCaracteristicas.Columns["StatusFlag"].Visible = false;
                gridCaracteristicas.Columns["Activo"].Visible = false;
            }
        }

        private void gridCaracteristicas_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (gridCaracteristicas.SelectedRows.Count > 0)
            {
                Entidades.Caracteristica selCaracteristica = gridCaracteristicas.SelectedRows[0].DataBoundItem as Entidades.Caracteristica;

                if (selCaracteristica != null)
                {
                    txtCaracteristica.Text = selCaracteristica.NombreCaracteristica;
                    txtDescrip.Text = selCaracteristica.Descripcion;
                }
            }
        }

        #endregion

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            LogicaNegocio.EquipoBLL equipoBLL = new LogicaNegocio.EquipoBLL();

            try
            {
                if (btnGuardar.Tag == null)
                {
                    Entidades.ListaTarifa newListaTarifa =
                        new Entidades.ListaTarifa()
                        {
                            Moneda = cmbMoneda.SelectedIndex >= 0 ? cmbMoneda.SelectedItem.ToString() : null,
                            HoraxDia = !string.IsNullOrWhiteSpace(txtnumDia.Text) ? Int32.Parse(txtnumDia.Text.Trim()) : new Nullable<int>(),
                            HoraxSemana = !string.IsNullOrWhiteSpace(txtnumSemana.Text) ? Int32.Parse(txtnumSemana.Text.Trim()) : new Nullable<int>(),
                            HoraxMes = !string.IsNullOrWhiteSpace(txtnumMes.Text) ? Int32.Parse(txtnumMes.Text.Trim()) : new Nullable<int>(),
                            TarifaHoraDia = !string.IsNullOrWhiteSpace(txtTarifaHoraDia.Text) ? decimal.Parse(txtTarifaHoraDia.Text.Trim()) : new Nullable<decimal>(),
                            TarifaHoraSemana = !string.IsNullOrWhiteSpace(txtTarifaHoraSemana.Text) ? decimal.Parse(txtTarifaHoraSemana.Text.Trim()) : new Nullable<decimal>(),
                            TarifaHoraMes = !string.IsNullOrWhiteSpace(txtTarifaHoraMes.Text) ? decimal.Parse(txtTarifaHoraMes.Text.Trim()) : new Nullable<decimal>(),
                            TarifaTotalDia = !string.IsNullOrWhiteSpace(txtTarifaDia.Text) ? decimal.Parse(txtTarifaDia.Text.Trim()) : new Nullable<decimal>(),
                            TarifaTotalSemana = !string.IsNullOrWhiteSpace(txtTarifaSemana.Text) ? decimal.Parse(txtTarifaSemana.Text.Trim()) : new Nullable<decimal>(),
                            TarifaTotalMes = !string.IsNullOrWhiteSpace(txtTarifaMes.Text) ? decimal.Parse(txtTarifaMes.Text.Trim()) : new Nullable<decimal>(),
                            Activo = 1
                        };

                    listListaTarifa.Clear();
                    listListaTarifa.Add(newListaTarifa);

                    Entidades.Equipo newEquipo =
                        new Entidades.Equipo()
                        {
                            IdModelo = cmbModelo.SelectedIndex >= 0 ? Int32.Parse(cmbModelo.SelectedValue.ToString()) : new Nullable<int>(),
                            CodigoEquipo = !string.IsNullOrWhiteSpace(txtCodigo.Text) ? txtCodigo.Text.Trim() : null,
                            NombreEquipo = !string.IsNullOrWhiteSpace(txtDescripcion.Text) ? txtDescripcion.Text.Trim() : null,
                            EsAlquiler = chkEsAlquiler.Checked ? 1 : new Nullable<int>(),
                            EsVenta = chkEsVenta.Checked ? 1 : new Nullable<int>(),
                            Activo = 1,
                            FechaRegistro = DateTime.Now,
                            UsuarioRegistro = string.Empty,
                            ListCaracteristica = listCaracteristica,
                            ListListaTarifa = listListaTarifa
                        };

                    int resultado = equipoBLL.Guardar(newEquipo);

                    if (resultado > 0)
                    {
                        MessageBox.Show("Equipo registrado", "Cotizav", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        
                        LimpiarTabInformacionBasica();
                        LimpiarTabListaTarifa();
                        LimpiarTabCaracteristica();
                    }
                }
            }
            catch (ApplicationException aex)
            {
                MessageBox.Show(aex.Message, "Cotizav", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            LimpiarTabInformacionBasica();
            LimpiarTabListaTarifa();
            LimpiarTabCaracteristica();
        }
    }
}
